/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.order.poa.controller;

import com.activiti.dao.model.Activiti_SubTaskInfoRO;
import com.activiti.dao.service.ActivitiService;
import com.activiti.dao.service.TaskSubService;
import com.erp.cux.workflow.controller.CuxControllerSupport;
import com.erp.dataset.service.DatasetCommonService;
import com.erp.hr.base.util.CommonUtils;
import com.erp.hr.dao.model.HrDepartment;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.order.poa.dao.model.PoAgreementHead;
import com.erp.order.poa.dao.model.PoAgreementHeadBase;
import com.erp.order.poa.dao.model.PoAgreementHeadCO;
import com.erp.order.poa.service.PoAgreementHeadService;


import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.hibernate.exception.ConstraintViolationException;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.util.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


import javax.validation.Valid;
import java.util.*;

@Controller
@RequestMapping("/web/poAgreementHeadStop")
public class PoAgreementHeadStopWebController extends CuxControllerSupport {

    //日志处理
    private Logger logger = LoggerFactory.getLogger(PoAgreementHeadStopWebController.class);

    //服务层注入
    @Autowired
    private PoAgreementHeadService poAgreementHeadService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private HrCommonService hrCommonService;
    @Autowired
    private ActivitiService activitiService;
    @Autowired
    private TaskSubService taskSubService;

    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getPoHeadList");
    }
    /**
     * 跳转到合同列表（或者合同终止列表）
     */
    @RequestMapping("getPoHeadList")
    public String getPoAgreementHeadList(Pages pages, PoAgreementHeadCO poAgreementHeadCO, Model model) {
        //分页查询数据
        if (pages.getPage() == 0) {
            pages.setPage(1);
        }
        //分页查询数据
        StringBuffer dataAuthSql = new StringBuffer();
        if (poAgreementHeadCO.getStatus() !=null && !"".equals(poAgreementHeadCO.getStatus())){
            dataAuthSql.append(" and p.created_by ='"+ShiroUtil.getPrincipal()+"'");
        }else{
            dataAuthSql.append(" and p.status in('CONFIRM','ALTER','CANCEL') and p.created_by ='"+ShiroUtil.getPrincipal()+"'");
        }
        List<PoAgreementHead> poAgreementHeadList = this.poAgreementHeadService.getDataObjectsForDataAuth(dataAuthSql.toString(), pages, poAgreementHeadCO);
        //合同性质
        Map poQualeMap = this.datasetCommonService.getPOType();
        //合同类型
        Map poTypeMap = this.datasetCommonService.getPOAType();
        //状态
        Map poStatusMap = this.datasetCommonService.getPOAStatus();
        //审批状态
        Map approveStatusMap = this.datasetCommonService.getApproveStatus();
        //获取供应商
        Map vendorMap = this.masterDataCommonService.getVendorMap();
        //页面属性设置
        model.addAttribute("poHeadList", poAgreementHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("poQualeMap", poQualeMap);
        model.addAttribute("poTypeMap", poTypeMap);
        model.addAttribute("poStatusMap", poStatusMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("vendorMap", vendorMap);
        return "basic.jsp?content=poa/poaStopList";
    }


    /**
     * 跳转合同终止流程审批界面
     * id 是任务id（taskid）
     */
    @RequestMapping("getPoHeadStopApproval")
    public String getPoHeadStopApproval(PoAgreementHeadBase poAgreementHead,String id, Model model) {
        //查询要编辑的数据
        PoAgreementHeadBase poAgreementHeadTemp = this.poAgreementHeadService.getDataObject(poAgreementHead.getPoHeadCode());
        if (poAgreementHeadTemp != null) {
            poAgreementHead = poAgreementHeadTemp;
        }
        if(poAgreementHead.getStopProcessInstanceId()!=null){
            //根据流程id获取流程审批信息
            List<Activiti_SubTaskInfoRO> activiti_subTaskInfoList = taskSubService.getDataObjects(poAgreementHead.getStopProcessInstanceId());
            model.addAttribute("subTaskInfoList", activiti_subTaskInfoList);
        }
        //合同性质
        Map poQualeMap = this.datasetCommonService.getPOType();
        //合同类型
        Map poTypeMap = this.datasetCommonService.getPOAType();
        //合同类别
        Map poCateMap = this.datasetCommonService.getPOACategory();
        //合同结算方式
        Map poSettleMap = this.datasetCommonService.getPOASettleStyle();
        //合同来源方式
        Map poSourceMap = this.datasetCommonService.getPOASourceMode();
        //币种
        Map currencyTypeMap = this.datasetCommonService.getCurrencyType();
        //获取供应商
        Map vendorMap = this.masterDataCommonService.getVendorMap();
        //状态
        Map poStatusMap = this.datasetCommonService.getPOAStatus();
        //页面属性设置
        model.addAttribute("poHead", poAgreementHead);
        model.addAttribute("poQualeMap", poQualeMap);
        model.addAttribute("poTypeMap", poTypeMap);
        model.addAttribute("poCateMap", poCateMap);
        model.addAttribute("poSettleMap", poSettleMap);
        model.addAttribute("poSourceMap", poSourceMap);
        model.addAttribute("currencyTypeMap", currencyTypeMap);
        model.addAttribute("poStatusMap", poStatusMap);
        model.addAttribute("vendorMap", vendorMap);
        model.addAttribute("taskId", id);
        if(poAgreementHead.getStopProcessInstanceId() != null && !"".equals(poAgreementHead.getStopProcessInstanceId())){
            return "basic.jsp?content=poa/poaStopApproval";
        }
        return "basic.jsp?content=poa/poaStopEdit";
    }

    /**
     * 跳转合同终止流程查看界面
     */
    @RequestMapping("getPoHeadStopView")
    public String getPoHeadStopView(PoAgreementHeadBase poAgreementHead,String id, Model model) {
        //查询要编辑的数据
        PoAgreementHeadBase poAgreementHeadTemp = this.poAgreementHeadService.getDataObject(poAgreementHead.getPoHeadCode());
        if (poAgreementHeadTemp != null) {
            poAgreementHead = poAgreementHeadTemp;
        }
        if(poAgreementHead.getStopProcessInstanceId()!=null){
            //根据流程id获取流程审批信息
            List<Activiti_SubTaskInfoRO> activiti_subTaskInfoList = taskSubService.getDataObjects(poAgreementHead.getStopProcessInstanceId());
            model.addAttribute("subTaskInfoList", activiti_subTaskInfoList);
        }
        //合同性质
        Map poQualeMap = this.datasetCommonService.getPOType();
        //合同类型
        Map poTypeMap = this.datasetCommonService.getPOAType();
        //合同类别
        Map poCateMap = this.datasetCommonService.getPOACategory();
        //合同结算方式
        Map poSettleMap = this.datasetCommonService.getPOASettleStyle();
        //合同来源方式
        Map poSourceMap = this.datasetCommonService.getPOASourceMode();
        //币种
        Map currencyTypeMap = this.datasetCommonService.getCurrencyType();
        //获取供应商
        Map vendorMap = this.masterDataCommonService.getVendorMap();
        //状态
        Map poStatusMap = this.datasetCommonService.getPOAStatus();
        //页面属性设置
        model.addAttribute("poHead", poAgreementHead);
        model.addAttribute("poQualeMap", poQualeMap);
        model.addAttribute("poTypeMap", poTypeMap);
        model.addAttribute("poCateMap", poCateMap);
        model.addAttribute("poSettleMap", poSettleMap);
        model.addAttribute("poSourceMap", poSourceMap);
        model.addAttribute("currencyTypeMap", currencyTypeMap);
        model.addAttribute("poStatusMap", poStatusMap);
        model.addAttribute("vendorMap", vendorMap);
        model.addAttribute("taskId", id);
        return "basic.jsp?content=poa/poaStopView";
    }

    /**
     * 启动合同终止审批流程
     */
    @RequestMapping("startPoaStopFlow")
    public String startPoaStopFlow(@Valid PoAgreementHead poAgreementHead, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        PoAgreementHead poAgreementHeadTemp = this.poAgreementHeadService.getDataObject(poAgreementHead.getPoHeadId());
        poAgreementHeadTemp.setStopReason(poAgreementHead.getStopReason());
        poAgreementHeadTemp.setIsSign(poAgreementHead.getIsSign());
        if (poAgreementHeadTemp != null) {
            poAgreementHead = poAgreementHeadTemp;
        }
        try {
            //获取当前用户职员信息
            HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
            HrDepartment hrDepartmentget=this.hrCommonService.getHrDepartmentParentCompany(staffInfo.getDepartmentCode());
            staffInfo.setCompanyName(hrDepartmentget.getDepartmentName());
            staffInfo.setCompanyCode(hrDepartmentget.getDepartmentCode());
            Map params = new HashMap<String, Object>();
            params.put("panen", staffInfo.getStaffCode());//发起人(单位/部门负责人提交审批)
            params.put("htzgsp_id_list", this.activitiService.getStaffByPosition("SPB","289"));//合同主管审批
            //启动流程
            ProcessInstance processInstance = activitiService.erpStartProcessInstance(CommonUtils.PROCESS_CLOSE_KEY,"web/poAgreementHeadStop/getPoHeadStopApproval?poHeadCode="+poAgreementHead.getPoHeadCode(),params,CommonUtils.ACTIVITI_AGREEMENT_BUS_ID);
            //更新流程实例id
            poAgreementHead.setStopProcessInstanceId(processInstance.getProcessInstanceId());
            poAgreementHead.setStatus("ALTER");
            this.poAgreementHeadService.updateDataObject(poAgreementHead);
            //流程发起者完成当前任务节点
            Task task = activitiService.erpFindPersonalTaskByPid(processInstance.getProcessInstanceId());
            if(task != null){
                activitiService.erpCompletTask(task.getId(),"1",null);
            }

            //保存审批结果和意见
            this.poAgreementHeadService.saveActivitiTaskInfo(poAgreementHead.getPoName()+"(合同终止)",staffInfo,task,processInstance,"1");
            this.poAgreementHeadService.saveSubActivitiTaskInfo(staffInfo,task,processInstance,"1","1",staffInfo.getStaffName()+"发起合同终止流程审批");
            attr.addFlashAttribute("hint", "success");
        } catch (Exception e) {
            if (e.getCause().getClass() == ConstraintViolationException.class) {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "合同终止流程启动失败");
                return "redirect:getPoHeadList";
            } else {
                throw e;
            }
        }
        return "redirect:getPoHeadList";
    }
}
